package com.nfit.util;

import cn.hutool.core.util.RandomUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class EmailUtils {
    private final JavaMailSender javaMailSender;
    private final String from;
    @Autowired
    private StringRedisTemplate template;

    public EmailUtils(JavaMailSender javaMailSender, @Value("${spring.mail.username}") String from) {
        this.javaMailSender = javaMailSender;
        this.from = from;
    }

    public String sendEmailWithCode(String email) {
        int code = RandomUtil.randomInt(100000, 999999);
        SimpleMailMessage message = new SimpleMailMessage();
        message.setFrom(from);
        message.setTo(email);
        message.setSubject("Your verification code");
        message.setText("Your code is: " + code);
        template.opsForValue().set(email, String.valueOf(code),600, TimeUnit.SECONDS);
        javaMailSender.send(message);
        return String.valueOf(code);
    }
}
